package com.nhutcm.trackingthief.utils.sendemail;

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * Send an Email via Gmail SMTP server using SSL connection.
 * 
 * @author Chau Minh Nhut (nhutcm@viettel.com.vn)
 * @see http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
 * @since 17/05/2014  
 * 
 */
public class GMailSender extends javax.mail.Authenticator {
	private String mailhost = "smtp.gmail.com";
	private String username;
	private String password;
	private Session session;

//	static {
//		Security.addProvider(new JSSEProvider());
//	}

	public GMailSender(String user, String password) {
		this.username = user;
		this.password = password;

		Properties props = new Properties();

		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");

		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", mailhost);
		props.setProperty("mail.smtp.quitwait", "false");

		session = Session.getDefaultInstance(props, this);
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, password);
	}

	public synchronized void sendMail(String subject, String body,
			String mailFrom, String mailTo) throws Exception {

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(mailFrom));
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(mailTo));
		message.setSubject(subject);
		message.setText(body);

		Transport.send(message);
	}

	public synchronized void sendMail(String subject, String body,
			String mailFrom, String mailTo, File attachment) throws Exception {
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(mailFrom));
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(mailTo));
		message.setSubject(subject);

		MimeBodyPart mbp1 = new MimeBodyPart();
		mbp1.setText(body);

		MimeBodyPart mbp2 = new MimeBodyPart();
		FileDataSource fds = new FileDataSource(attachment);
		mbp2.setDataHandler(new DataHandler(fds));
		mbp2.setFileName(fds.getName());

		Multipart mp = new MimeMultipart();
		mp.addBodyPart(mbp1);
		mp.addBodyPart(mbp2);

		message.setContent(mp);
		Transport.send(message);
	}
}